<template>
  <div class="app-container">
    <el-form ref="form" :model="form" :rules="rules" label-width="100px">
      <!-- 基础信息 -->
      <el-card shadow="never">
        <div slot="header" class="clearfix">
          <span>基础信息</span>
        </div>
        <el-row>
          <el-col :span="8">
            <el-form-item label="生产订单号" prop="prodOrderCode">
              <el-input v-model="form.prodOrderCode" placeholder="请输入生产订单号" :disabled="true" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="销售订单号" prop="salesOrderCode">
              <el-input v-model="form.salesOrderCode" placeholder="销售订单号" :disabled="true" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="订单状态" prop="status">
              <el-select v-model="form.status" placeholder="请选择状态" style="width:100%">
                <el-option
                  v-for="dict in statusOptions"
                  :key="dict.dictValue"
                  :label="dict.dictLabel"
                  :value="dict.dictValue"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="优先级" prop="priority">
              <el-select v-model="form.priority" placeholder="请选择优先级" style="width:100%">
                <el-option
                  v-for="dict in priorityOptions"
                  :key="dict.dictValue"
                  :label="dict.dictLabel"
                  :value="dict.dictValue"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="交付日期" prop="deliveryDate">
              <el-date-picker
                v-model="form.deliveryDate"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="选择日期"
                style="width:100%"
              ></el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
             <el-form-item label="备注" prop="remark">
                <el-input v-model="form.remark" type="textarea" :rows="3" placeholder="请输入内容" />
              </el-form-item>
           </el-col>
        </el-row>
      </el-card>

      <!-- 产品信息 -->
      <el-card shadow="never" style="margin-top: 20px;">
        <div slot="header" class="clearfix">
          <span>产品信息</span>
        </div>
        <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
                <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAddProduct">添加产品</el-button>
            </el-col>
        </el-row>
        <el-table :data="productList" style="width: 100%; margin-top: 10px;" border>
            <el-table-column label="序号" type="index" width="55" align="center" />
            <el-table-column label="产品编码" prop="productCode" align="center" />
            <el-table-column label="产品名称" prop="productName" align="center" />
            <el-table-column label="规格" prop="productSfn" align="center" />
            <el-table-column label="计量单位" prop="productUnit" align="center" />
            <el-table-column label="计划产量" align="center" width="150">
                <template slot-scope="scope">
                    <el-input-number v-model="scope.row.qtyNum" :min="1" size="small" :precision="0"></el-input-number>
                </template>
            </el-table-column>
            <el-table-column label="交付日期" align="center" width="200">
                <template slot-scope="scope">
                     <el-date-picker v-model="scope.row.deliveryDate" type="date" placeholder="选择日期" size="small" value-format="yyyy-MM-dd"></el-date-picker>
                </template>
            </el-table-column>
            <el-table-column label="操作" align="center" width="80">
                <template slot-scope="scope">
                    <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDeleteProduct(scope.$index)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>
      </el-card>
      
      <div style="text-align: center; margin-top: 30px;">
        <el-button @click="onCancel">取 消</el-button>
        <el-button type="primary" @click="onSubmit">保 存</el-button>
      </div>

    </el-form>

    <!-- 选择产品弹窗 -->
    <el-dialog title="选择产品" :visible.sync="selectProductDialogVisible" width="800px" append-to-body>
      <el-form :model="productQueryParams" ref="productQueryForm" size="small" :inline="true">
        <el-form-item label="产品编码" prop="productCode">
          <el-input
            v-model="productQueryParams.productCode"
            placeholder="请输入产品编码"
            clearable
            @keyup.enter.native="handleProductQuery"
          />
        </el-form-item>
        <el-form-item label="产品名称" prop="productName">
          <el-input
            v-model="productQueryParams.productName"
            placeholder="请输入产品名称"
            clearable
            @keyup.enter.native="handleProductQuery"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleProductQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetProductQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <el-table v-loading="productLoading" :data="selectableProducts" @selection-change="handleProductSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="产品编码" align="center" prop="productcode" />
        <el-table-column label="产品名称" align="center" prop="productname" />
        <el-table-column label="规格" align="center" prop="specificationnumber" />
        <el-table-column label="单位" align="center" prop="unit" width="100" />
      </el-table>
      
      <pagination
        v-show="productTotal>0"
        :total="productTotal"
        :page.sync="productQueryParams.pageNum"
        :limit.sync="productQueryParams.pageSize"
        @pagination="getProductList"
      />

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="confirmSelectProduct">确 定</el-button>
        <el-button @click="selectProductDialogVisible = false">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { getProductionOrder, updateProductionOrder } from "@/api/sc/productionOrder";
import { listProduct } from "@/api/sc/product";

export default {
  name: "EditOrder",
  data() {
    return {
      // 订单ID
      orderId: null,
      // 表单参数
      form: {
        id: undefined,
        prodOrderCode: undefined,
        salesOrderId: undefined,
        salesOrderCode: undefined,
        status: undefined,
        priority: undefined,
        deliveryDate: undefined,
        remark: undefined
      },
      // 产品列表
      productList: [],
      // 状态选项
      statusOptions: [],
      // 优先级选项
      priorityOptions: [],
      // 表单校验
      rules: {
        status: [
          { required: true, message: "订单状态不能为空", trigger: "change" }
        ],
        priority: [
          { required: true, message: "优先级不能为空", trigger: "change" }
        ],
        deliveryDate: [
          { required: true, message: "交付日期不能为空", trigger: "change" }
        ]
      },
      // 选择产品弹窗相关
      selectProductDialogVisible: false,
      productQueryParams: {
        pageNum: 1,
        pageSize: 10,
        productCode: '',
        productName: ''
      },
      productLoading: false,
      selectableProducts: [],
      productTotal: 0,
      selectedProducts: [],
    };
  },
  created() {
    this.orderId = this.$route.query.id;
    console.log("当前订单ID:", this.orderId);

    // 获取字典数据
    this.getDicts("sc_production_status").then(response => {
      this.statusOptions = response.data;
    });
    this.getDicts("sc_priority_type").then(response => {
      this.priorityOptions = response.data;
    });
    this.getOrderInfo();
  },
  watch: {
    // 监听路由变化，页面重新加载时刷新数据
    '$route'(to) {
      if (to.path === '/sc/order/edit' || to.name === 'EditOrder') {
        console.log('编辑订单页面路由变化，刷新数据');
        this.orderId = to.query.id;
        if (this.orderId) {
          this.getOrderInfo();
        }
      }
    },
    // 监听订单ID变化
    orderId(newVal, oldVal) {
      if (newVal && newVal !== oldVal) {
        console.log('订单ID变化，刷新编辑数据');
        this.getOrderInfo();
      }
    }
  },
  methods: {
    // 获取订单信息
    getOrderInfo() {
      if (!this.orderId) {
        this.$message.error("订单ID不能为空");
        return;
      }
      
      console.log("开始获取订单信息，ID:", this.orderId);
      
      getProductionOrder(this.orderId).then(response => {
        console.log("订单API响应完整数据:", response);
        console.log("订单数据:", response.data);
        
        // 设置基础信息
        this.form = response.data;
        
        // 确保日期格式正确
        if (this.form.deliveryDate) {
          // 如果是字符串格式，转换为Date对象
          if (typeof this.form.deliveryDate === 'string') {
            // 移除可能的时间部分，只保留日期
            const dateStr = this.form.deliveryDate.split(' ')[0].split('T')[0];
            this.form.deliveryDate = new Date(dateStr);
          }
          console.log("处理后的交付日期:", this.form.deliveryDate);
        }
        
        // 检查各种可能的产品详情字段
        console.log("检查产品列表字段:");
        if (response.data && response.data.details) {
          console.log("- details字段:", response.data.details);
        }
        if (response.data && response.data.productDetails) {
          console.log("- productDetails字段:", response.data.productDetails);
        }
        if (response.data && response.data.items) {
          console.log("- items字段:", response.data.items);
        }
        if (response.data && response.data.products) {
          console.log("- products字段:", response.data.products);
        }
        
        // 尝试从不同字段获取产品列表
        if (response.data && response.data.products && response.data.products.length > 0) {
          this.productList = response.data.products;
          console.log("从products字段获取产品明细:", this.productList);
        } else if (response.data && response.data.details && response.data.details.length > 0) {
          this.productList = response.data.details;
          console.log("从details字段获取产品明细:", this.productList);
        } else if (response.data && response.data.productDetails && response.data.productDetails.length > 0) {
          this.productList = response.data.productDetails;
          console.log("从productDetails字段获取产品明细:", this.productList);
        } else if (response.data && response.data.items && response.data.items.length > 0) {
          this.productList = response.data.items;
          console.log("从items字段获取产品明细:", this.productList);
        } else {
          console.warn("未找到产品明细数据，尝试单独获取");
          this.getOrderDetails();
          return;
        }
        
        // 属性名称适配
        this.productList = this.productList.map(item => {
          return {
            productId: item.productId,
            productCode: item.productCode || item.product_code || item.code || '',
            productName: item.productName || item.product_name || item.name || '',
            productSfn: item.productSfn || item.specification || item.specs || '',
            productUnit: item.productUnit || item.unit || item.unitName || 'PCS',
            qtyNum: item.qtyNum || item.plannedQty || item.qty || item.quantity || 0,
            deliveryDate: item.deliveryDate || item.delivery_date || this.form.deliveryDate
          };
        });
        
        console.log("最终处理后的产品列表:", this.productList);
      }).catch(error => {
        console.error("获取订单信息失败:", error);
        this.$message.error("获取订单信息失败");
      });
    },
    
    // 单独获取订单明细（当主接口没有返回明细数据时使用）
    getOrderDetails() {
      console.log("尝试单独获取订单明细");
      
      // 可以在这里添加单独的API调用来获取订单明细
    },
    
    // 添加产品按钮
    handleAddProduct() {
        this.openSelectProductDialog();
    },
    // 删除产品行
    handleDeleteProduct(index) {
        this.productList.splice(index, 1);
    },
    // 打开选择产品弹窗
    openSelectProductDialog() {
      this.selectProductDialogVisible = true;
      this.selectedProducts = [];
      this.getProductList();
    },
    // 获取产品列表
    getProductList() {
      this.productLoading = true;
      listProduct(this.productQueryParams).then(response => {
        this.selectableProducts = response.rows.map((product, index) => ({
          ...product,
          productid: product.product_id || product.productId || product.productid || index + 1,
          productcode: product.product_code || product.productCode || product.productcode || `TEMP-${index + 1}`,
          productname: product.product_name || product.productName || product.productname || `未命名产品-${index + 1}`,
          specificationnumber: product.product_sfn || product.specification || product.specificationnumber || '',
          unit: product.product_unit || product.unit || '件',
        }));
        this.productTotal = response.total;
        this.productLoading = false;
      });
    },
    // 处理产品查询
    handleProductQuery() {
      this.productQueryParams.pageNum = 1;
      this.getProductList();
    },
    // 重置产品查询
    resetProductQuery() {
      this.resetForm("productQueryForm");
      this.handleProductQuery();
    },
    // 处理产品选择
    handleProductSelectionChange(selection) {
      this.selectedProducts = selection;
    },
    // 确认选择产品
    confirmSelectProduct() {
      if (this.selectedProducts.length === 0) {
        this.$message.warning("请至少选择一个产品");
        return;
      }
      
      this.selectedProducts.forEach(product => {
        const productId = Number(product.productid);
        if (!productId) {
          console.error("产品ID无效:", product);
          return;
        }
        
        const existIndex = this.productList.findIndex(item => Number(item.productId) === productId);
        if (existIndex !== -1) {
          this.$message.warning(`产品 ${product.productname} 已添加，请勿重复添加`);
          return;
        }
        
        this.productList.push({
          productId: productId,
          productCode: product.productcode,
          productName: product.productname,
          productSfn: product.specificationnumber,
          productUnit: product.unit,
          qtyNum: 1,
          deliveryDate: this.form.deliveryDate,
        });
      });
      
      this.selectProductDialogVisible = false;
    },
    
    // 保存按钮
    onSubmit() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (!this.productList || this.productList.length === 0) {
            this.$message.warning("请至少添加一个产品。");
            return;
          }

          // 构建提交数据，包含产品列表
          const submitData = {
            ...this.form,
            products: this.productList
          };
          
          // 移除不必要的字段
          delete submitData.stockCheck;
          delete submitData.stockEnough;
          
          console.log("准备提交的数据:", submitData);
          
          updateProductionOrder(submitData).then(response => {
            console.log("更新响应:", response);
            this.$modal.msgSuccess("修改成功");
            this.closePage();
          }).catch(error => {
            console.error("更新订单失败:", error);
            
            // 处理404错误 - 临时解决方案
            if (error.response && error.response.status === 404) {
              this.$confirm('保存接口暂未实现，是否仍要关闭页面？', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
              }).then(() => {
                this.closePage();
              }).catch(() => {});
            } else {
              this.$message.error("更新订单失败: " + (error.message || "未知错误"));
            }
          });
        }
      });
    },
    // 取消按钮
    onCancel() {
      this.closePage();
    },
    // 关闭页面
    closePage() {
      this.$store.dispatch("tagsView/delView", this.$route);
      this.$router.go(-1);
    }
  }
};
</script>

<style scoped>
.box-card {
  width: 100%;
}
</style> 